'use client';
import React, { useRef, useEffect, useState, useCallback } from 'react';
import Webcam from 'react-webcam';
import styles from './page.module.css';
const img1 = '/avatars/1.jpg';
const img2 = '/avatars/2.jpg';
import Peer from 'peerjs';
import { FaMicrophone, FaMicrophoneSlash, FaVideo, FaVideoSlash, FaSignal, FaUsers, FaRegSmile, FaMobile, FaDesktop, FaWifi, FaShareAlt, FaLink, FaCopy, FaCheck } from 'react-icons/fa';
import { QRCodeSVG } from 'qrcode.react';
// import { useRouter } from 'next/router';

const url = 'http://192.168.221.119:3000/liveview?id=broadcaster';

// Define types for the component's state and props
type DeviceType = 'mobile' | 'desktop';
type NetworkStatus = 'excellent' | 'good' | 'poor';
type StreamQuality = '标清' | '高清' | '超清';
type DeviceKind = 'videoinput' | 'audioinput';

interface DeviceInfo {
  deviceId: string;
  groupId: string;
  kind: MediaDeviceKind;
  label: string;
}

interface AvailableDevices {
  videoinput: DeviceInfo[];
  audioinput: DeviceInfo[];
}

interface SelectedDevices {
  videoinput: string;
  audioinput: string;
}

interface Danmaku {
  id: number;
  text: string;
  top: number;
}

interface GiftAnimation {
  icon?: string;
  name?: string;
}

const LiveRoom = () => {
  // const router = useRouter();
  
  // State with TypeScript types
  const [viewerCount, setViewerCount] = useState<number>(0);
  const webcamRef = useRef<Webcam>(null);
  const [peerId, setPeerId] = useState<string>('');
  const peerRef = useRef<Peer | null>(null);
  const [danmakuList, setDanmakuList] = useState<Danmaku[]>([]);
  const [giftAnimation, setGiftAnimation] = useState<GiftAnimation | null>(null);
  const [isLive, setIsLive] = useState<boolean>(false);
  const [audioEnabled, setAudioEnabled] = useState<boolean>(true);
  const [videoEnabled, setVideoEnabled] = useState<boolean>(true);
  const [streamQuality, setStreamQuality] = useState<StreamQuality>('高清');
  const [deviceType, setDeviceType] = useState<DeviceType>('desktop');
  const [networkStatus, setNetworkStatus] = useState<NetworkStatus>('good');
  const [localIpAddress, setLocalIpAddress] = useState<string>('');
  const [showShareLink, setShowShareLink] = useState<boolean>(false);
  const [linkCopied, setLinkCopied] = useState<boolean>(false);
  const [availableDevices, setAvailableDevices] = useState<AvailableDevices>({
    videoinput: [],
    audioinput: []
  });
  const [selectedDevices, setSelectedDevices] = useState<SelectedDevices>({
    videoinput: '',
    audioinput: ''
  });
  const [showDeviceSelector, setShowDeviceSelector] = useState<boolean>(false);

  // Device type detection
  useEffect(() => {
    const checkDeviceType = () => {
      const isMobile = /iPhone|iPad|iPod|Android/i.test(navigator.userAgent);
      setDeviceType(isMobile ? 'mobile' : 'desktop');
    };

    checkDeviceType();

    const getLocalIpAddress = async () => {
      try {
        const pc = new RTCPeerConnection({
          iceServers: []
        });
        pc.createDataChannel('');
        await pc.createOffer().then(offer => pc.setLocalDescription(offer));

        await new Promise<void>(resolve => {
          pc.onicecandidate = (ice) => {
            if (ice.candidate) {
              const ipRegex = /([0-9]{1,3}(\.[0-9]{1,3}){3})/;
              const ipMatch = ipRegex.exec(ice.candidate.candidate);
              if (ipMatch && ipMatch[1] && !ipMatch[1].startsWith('127.')) {
                setLocalIpAddress(ipMatch[1]);
                resolve();
              }
            }
          };

          setTimeout(resolve, 5000);
        });

        pc.close();
      } catch (error) {
        console.error('获取本地IP地址失败:', error);
        try {
          const response = await fetch('/api/get-ip');
          const data = await response.json();
          if (data.ip) {
            setLocalIpAddress(data.ip);
          }
        } catch (err) {
          console.error('备用IP获取方法失败:', err);
          setLocalIpAddress('请连接到WiFi网络');
        }
      }
    };

    getLocalIpAddress();

    const handleResize = () => {
      checkDeviceType();
    };

    window.addEventListener('resize', handleResize);
    return () => window.removeEventListener('resize', handleResize);
  }, []);

  // Media devices enumeration
  useEffect(() => {
    const getAvailableDevices = async () => {
      try {
        await navigator.mediaDevices.getUserMedia({ video: true, audio: true });

        const devices = await navigator.mediaDevices.enumerateDevices();

        const videoDevices = devices.filter(device => device.kind === 'videoinput');
        const audioDevices = devices.filter(device => device.kind === 'audioinput');

        setAvailableDevices({
          videoinput: videoDevices,
          audioinput: audioDevices
        });

        if (videoDevices.length > 0) {
          setSelectedDevices(prev => ({
            ...prev,
            videoinput: videoDevices[0].deviceId
          }));
        }

        if (audioDevices.length > 0) {
          setSelectedDevices(prev => ({
            ...prev,
            audioinput: audioDevices[0].deviceId
          }));
        }
      } catch (error) {
        console.error('获取设备失败:', error);
      }
    };

    getAvailableDevices();
  }, []);

  // Network status monitoring
  useEffect(() => {
    const checkNetworkStatus = () => {
      if ('connection' in navigator) {
        const connection = navigator.connection || navigator.mozConnection || navigator.webkitConnection;

        if (connection) {
          const updateNetworkStatus = () => {
            const effectiveType = connection.effectiveType;
            const downlink = connection.downlink;

            if (effectiveType === '4g' && downlink > 5) {
              setNetworkStatus('excellent');
              setStreamQuality('超清');
            } else if (effectiveType === '4g' || (effectiveType === '3g' && downlink > 1)) {
              setNetworkStatus('good');
              setStreamQuality('高清');
            } else {
              setNetworkStatus('poor');
              setStreamQuality('标清');
            }
          };

          updateNetworkStatus();
          connection.addEventListener('change', updateNetworkStatus);
          return () => connection.removeEventListener('change', updateNetworkStatus);
        }
      }

      const pingTest = setInterval(() => {
        const start = Date.now();
        fetch('https://www.google.com', { mode: 'no-cors' })
          .then(() => {
            const duration = Date.now() - start;
            if (duration < 100) {
              setNetworkStatus('excellent');
            } else if (duration < 300) {
              setNetworkStatus('good');
            } else {
              setNetworkStatus('poor');
            }
          })
          .catch(() => setNetworkStatus('poor'));
      }, 30000);

      return () => clearInterval(pingTest);
    };

    const cleanup = checkNetworkStatus();
    return cleanup;
  }, []);

  // Main WebRTC effect
  useEffect(() => {
    if (!isLive) return;

    const peer = new Peer('broadcaster', {
      host: typeof window !== 'undefined' ? window.location.hostname : 'localhost',
      port: 9000,
      path: '/myapp',
      secure: false,
      debug: 3,
      config: {
        iceServers: [
          { urls: 'stun:stun.l.google.com:19302' },
          { urls: 'stun:stun1.l.google.com:19302' },
          { urls: 'stun:stun2.l.google.com:19302' }
        ]
      }
    });
    peerRef.current = peer;

    peer.on('open', (id) => {
      setPeerId(id);
      console.log('Broadcaster ID:', id);
    });

    peer.on('error', (err) => {
      console.error('PeerJS error:', err);
    });

    peer.on('connection', (conn) => {
      conn.on('open', () => {
        console.log('Viewer connected');
        setViewerCount(prev => prev + 1);

        conn.send({
          type: 'broadcaster_info',
          deviceType: deviceType,
          networkStatus: networkStatus,
          streamQuality: streamQuality
        });

        conn.peerConnection.onicecandidate = (event) => {
          if (event.candidate) {
            conn.send({
              type: 'ice_candidate',
              candidate: event.candidate
            });
          }
        };

        navigator.mediaDevices.getUserMedia({
          video: selectedDevices.videoinput ? { deviceId: { exact: selectedDevices.videoinput } } : true,
          audio: selectedDevices.audioinput ? { deviceId: { exact: selectedDevices.audioinput } } : true
        })
          .then((stream) => {
            if (webcamRef.current && webcamRef.current.video) {
              webcamRef.current.video.srcObject = stream;
            }

            const videoTracks = stream.getVideoTracks();
            if (videoTracks.length > 0) {
              const videoTrack = videoTracks[0];
              let constraints = {};

              if (networkStatus === 'poor') {
                constraints = {
                  width: { ideal: 640 },
                  height: { ideal: 360 },
                  frameRate: { max: 15 }
                };
              } else if (networkStatus === 'good') {
                constraints = {
                  width: { ideal: 1280 },
                  height: { ideal: 720 },
                  frameRate: { max: 30 }
                };
              } else {
                constraints = {
                  width: { ideal: 1920 },
                  height: { ideal: 1080 },
                  frameRate: { max: 30 }
                };
              }

              videoTrack.applyConstraints(constraints)
                .catch(e => console.error('无法应用视频约束:', e));
            }

            const call = peer.call(conn.peer, stream);

            call.on('stream', (remoteStream) => {
              console.log('Stream sent to viewer');
            });

            call.on('close', () => {
              console.log('Call closed');
            });
          })
          .catch((error) => {
            console.error('无法获取摄像头:', error);
            conn.send({
              type: 'error',
              message: '主播摄像头或麦克风访问失败'
            });
          });

        conn.on('data', (data: any) => {
          if (data.type === 'danmaku') {
            const newDanmaku: Danmaku = {
              id: Date.now(),
              text: data.text,
              top: Math.random() * 70 + 10,
            };
            setDanmakuList(prev => [...prev, newDanmaku]);
            setTimeout(() => {
              setDanmakuList(prev => prev.filter(d => d.id !== newDanmaku.id));
            }, 8000);
          } else if (data.type === 'gift') {
            setGiftAnimation(data.gift);
            setTimeout(() => setGiftAnimation(null), 3000);
          } else if (data.type === 'viewer_info') {
            console.log('观众设备信息:', data.deviceType);
          }
        });

        conn.on('close', () => {
          console.log('Viewer disconnected');
          setViewerCount(prev => Math.max(0, prev - 1));
        });
      });
    });

    return () => {
      if (peerRef.current) {
        peerRef.current.destroy();
      }
    };
  }, [isLive, deviceType, networkStatus, streamQuality, selectedDevices]);

  const toggleLivestream = () => {
    setIsLive(!isLive);
    if (!isLive) {
      console.log('开始直播');
    } else {
      setViewerCount(0);
      console.log('结束直播');
    }
  };

  const toggleAudio = () => {
    setAudioEnabled(!audioEnabled);
    if (webcamRef.current && webcamRef.current.video && webcamRef.current.video.srcObject) {
      const stream = webcamRef.current.video.srcObject as MediaStream;
      stream.getAudioTracks().forEach(track => {
        track.enabled = !audioEnabled;
      });
    }
  };

  const toggleVideo = () => {
    setVideoEnabled(!videoEnabled);
    if (webcamRef.current && webcamRef.current.video && webcamRef.current.video.srcObject) {
      const stream = webcamRef.current.video.srcObject as MediaStream;
      stream.getVideoTracks().forEach(track => {
        track.enabled = !videoEnabled;
      });
    }
  };

  const toggleStreamQuality = () => {
    const qualities: StreamQuality[] = ['标清', '高清', '超清'];
    const currentIndex = qualities.indexOf(streamQuality);
    const nextIndex = (currentIndex + 1) % qualities.length;
    setStreamQuality(qualities[nextIndex]);

    if (peerRef.current && peerRef.current.connections) {
      Object.values(peerRef.current.connections).forEach((connections: any[]) => {
        connections.forEach(conn => {
          if (conn.open) {
            conn.send({
              type: 'quality_change',
              quality: qualities[nextIndex]
            });
          }
        });
      });
    }
  };

  const changeDevice = (kind: DeviceKind, deviceId: string) => {
    setSelectedDevices(prev => ({
      ...prev,
      [kind]: deviceId
    }));

    if (isLive && webcamRef.current && webcamRef.current.video) {
      navigator.mediaDevices.getUserMedia({
        video: kind === 'videoinput' ? { deviceId: { exact: deviceId } } : true,
        audio: kind === 'audioinput' ? { deviceId: { exact: deviceId } } : true
      })
        .then(stream => {
          if (webcamRef.current && webcamRef.current.video) {
            webcamRef.current.video.srcObject = stream;
          }

          if (peerRef.current && peerRef.current.connections) {
            Object.values(peerRef.current.connections).forEach((connections: any[]) => {
              connections.forEach(conn => {
                if (conn.peerConnection) {
                  const senders = conn.peerConnection.getSenders();
                  senders.forEach((sender:any)=> {
                    if (sender.track.kind === (kind === 'videoinput' ? 'video' : 'audio')) {
                      const track = stream.getTracks().find(t => t.kind === sender.track.kind);
                      if (track) sender.replaceTrack(track);
                    }
                  });
                }
              });
            });
          }
        })
        .catch(error => console.error('切换设备失败:', error));
    }
  };

  return (
    <>
      <div className={styles.appContainer}>
        <div className={styles.element1}>
          <div>
            <img src={img1} alt="图片1" />
          </div>
          <div>
            <span>Z</span>
            <p>{viewerCount} 人观看</p>
          </div>
        </div>

        <div className={styles.element2}></div>

        <div className={styles.element3}>
          <img src={img2} alt="图片2" />
          <span>1</span>
        </div>

        <div className={styles.closeButton}>
          {/* <span onClick={() =>  router.push('/')}>×</span> */}
        </div>
      </div>

      <div className={styles.broadcasterContainer}>
        <div className={styles.webcamContainer}>
          <div className={`${styles.liveIndicator} ${isLive ? styles.active : ''}`}>
            <span className={styles.liveIcon}></span>
            {isLive ? 'LIVE' : '未开播'}
          </div>

          {isLive && (
            <div className={styles.shareButton} onClick={() => setShowShareLink(!showShareLink)}>
              <FaShareAlt /> 分享直播
            </div>
          )}

          {showShareLink && (
            <div className={styles.sharePopup}>
              <div className={styles.sharePopupHeader}>
                <h3>分享到局域网</h3>
                <span className={styles.closePopup} onClick={() => setShowShareLink(false)}>×</span>
              </div>
              <div className={styles.sharePopupContent}>
                <p>复制以下链接分享给同一局域网内的朋友：</p>
                <div className={styles.linkContainer}>
                  <FaLink />
                  <input
                    type="text"
                    readOnly
                    value={url}
                    className={styles.shareLink}
                  />
                  <button className={styles.copyButton} onClick={() => {
                    navigator.clipboard.writeText(url)
                      .then(() => {
                        setLinkCopied(true);
                        setTimeout(() => setLinkCopied(false), 2000);
                      })
                      .catch(err => console.error('复制失败:', err));
                  }}>
                    {linkCopied ? <FaCheck /> : <FaCopy />}
                  </button>
                </div>
                <div className={styles.qrContainer}>
                  <p>或扫描二维码：</p>
                  <div className={styles.qrPlaceholder}>
                    {localIpAddress && (
                      <QRCodeSVG
                        value={url}
                        size={150}
                        bgColor={"#ffffff"}
                        fgColor={"#000000"}
                        level={"L"}
                        includeMargin={true}
                      />
                    )}
                  </div>
                </div>
                <p className={styles.shareNote}>注意：确保接收方与您在同一个WiFi网络下</p>
              </div>
            </div>
          )}

          <div className={styles.viewerIndicator}>
            <FaUsers /> {viewerCount}
          </div>

          <div className={styles.qualityIndicator} onClick={toggleStreamQuality}>
            <FaSignal /> {streamQuality}
          </div>

          <div className={styles.deviceIndicator}>
            {deviceType === 'mobile' ? <FaMobile /> : <FaDesktop />} {deviceType === 'mobile' ? '移动设备' : '桌面设备'}
          </div>

          <div className={`${styles.networkIndicator} ${styles[networkStatus]}`}>
            <FaWifi /> {networkStatus === 'excellent' ? '极佳' : networkStatus === 'good' ? '良好' : '一般'}
          </div>

          <button
            className={`${styles.controlButton} ${styles.deviceButton}`}
            onClick={() => setShowDeviceSelector(!showDeviceSelector)}
          >
            切换设备
          </button>

          {showDeviceSelector && (
            <div className={styles.deviceSelector}>
              <div className={styles.deviceGroup}>
                <h3>摄像头</h3>
                {availableDevices.videoinput.map(device => (
                  <div
                    key={device.deviceId}
                    className={`${styles.deviceOption} ${selectedDevices.videoinput === device.deviceId ? styles.selected : ''}`}
                    onClick={() => changeDevice('videoinput', device.deviceId)}
                  >
                    {device.label || `摄像头 ${availableDevices.videoinput.indexOf(device) + 1}`}
                  </div>
                ))}
              </div>
              <div className={styles.deviceGroup}>
                <h3>麦克风</h3>
                {availableDevices.audioinput.map(device => (
                  <div
                    key={device.deviceId}
                    className={`${styles.deviceOption} ${selectedDevices.audioinput === device.deviceId ? styles.selected : ''}`}
                    onClick={() => changeDevice('audioinput', device.deviceId)}
                  >
                    {device.label || `麦克风 ${availableDevices.audioinput.indexOf(device) + 1}`}
                  </div>
                ))}
              </div>
            </div>
          )}

          {videoEnabled ? (
            <Webcam ref={webcamRef} mirrored={true} />
          ) : (
            <div className={styles.videoDisabled}>
              <FaVideoSlash size={50} />
              <p>摄像头已关闭</p>
            </div>
          )}

          <div className={styles.danmakuContainer}>
            {danmakuList.map((danmaku) => (
              <div
                key={danmaku.id}
                className={styles.danmaku}
                style={{ top: `${danmaku.top}%` }}
              >
                {danmaku.text}
              </div>
            ))}
          </div>

          {giftAnimation && (
            <div className={styles.giftAnimation}>
              <div className={styles.giftHeader}>收到礼物</div>
              <span>{giftAnimation.icon}</span>
              <div className={styles.giftName}>{giftAnimation.name || '礼物'}</div>
            </div>
          )}

          <div className={styles.overlayText}>
            {isLive ? '直播中...' : '准备开播'}
          </div>
          <div className={styles.overlayText1}></div>
          <div className={styles.overlayText2}>
            <span>PK</span>
            <span>连线</span>
          </div>

          <div className={`${styles.controlPanel} ${deviceType === 'mobile' ? styles.mobileControls : ''}`}>
            <button
              className={`${styles.controlButton} ${isLive ? styles.stopButton : styles.startButton}`}
              onClick={toggleLivestream}
            >
              {isLive ? '结束直播' : '开始直播'}
            </button>

            <button
              className={`${styles.controlButton} ${!audioEnabled ? styles.disabled : ''}`}
              onClick={toggleAudio}
            >
              {audioEnabled ? <FaMicrophone /> : <FaMicrophoneSlash />}
            </button>

            <button
              className={`${styles.controlButton} ${!videoEnabled ? styles.disabled : ''}`}
              onClick={toggleVideo}
            >
              {videoEnabled ? <FaVideo /> : <FaVideoSlash />}
            </button>

            <button className={styles.controlButton}>
              <FaRegSmile />
            </button>
          </div>
        </div>
        <h2 className={styles.broadcasterTitle}>
          {isLive ? '📡 直播中' : '🎬 主播端'}
        </h2>
      </div>
    </>
  );
};

export default LiveRoom;